<template>
  <div class="w-1/2">
    <h1 class="text-xl font-semibold leading-7 text-gray-900 mt-8">
      {{ $t('pageNetwork.staticDns') }}
    </h1>
    <el-row justify="end" class="mb-2">
      <el-button type="primary" :icon="CirclePlus" @click="initAddDns">
        {{ $t('pageNetwork.table.addDnsAddress') }}
      </el-button>
    </el-row>

    <el-table
      ref="tableRef"
      row-key="groupName"
      style="width: 100%"
      :data="form.dnsStaticTableItems"
      border
    >
      <el-table-column
        prop="Address"
        :label="$t('pageNetwork.table.ipAddress')"
      />
      <el-table-column label="Operations">
        <template #default="scope">
          <el-button
            size="small"
            type="danger"
            class="bg-orange-600"
            @click="deleteDnsTableRow(scope.$index)"
          >
            {{ $t('global.action.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { CirclePlus } from '@element-plus/icons-vue';
import { useNetworkStore } from '@/store/Settings/NetworkStore';
import { useI18n } from 'vue-i18n';

const i18n = useI18n();

const networkStore = useNetworkStore();

const props = defineProps<{ tabIndex: number }>();

const ethernetData = computed(() => networkStore.ethernetData);

const emit = defineEmits(['open-dns']);
const form = reactive({
  dnsStaticTableItems: [],
});

const getStaticDnsItems = () => {
  const index = props.tabIndex;
  const dns = ethernetData.value[index].StaticNameServers || [];
  form.dnsStaticTableItems = dns.map((server: any) => {
    return {
      address: server,
      actions: [
        {
          value: 'delete',
          title: i18n.t('pageNetwork.table.deleteDns'),
        },
      ],
    };
  });
};

const deleteDnsTableRow = (index: number) => {
  form.dnsStaticTableItems.splice(index, 1);
  const newDnsArray = form.dnsStaticTableItems.map((dns: { address: any }) => {
    return dns.address;
  });
  networkStore
    .editDnsAddress(newDnsArray)
    .then((message: string) =>
      ElNotification({
        title: 'Success',
        message,
        type: 'success',
      }),
    )
    .catch(({ message }: { message: string }) =>
      ElNotification({
        title: 'Error',
        message,
        type: 'error',
      }),
    );
};

const initAddDns = () => {
  emit('open-dns');
};

getStaticDnsItems();

watch(ethernetData, () => {
  getStaticDnsItems();
});
watch(
  () => props.tabIndex,
  () => {
    getStaticDnsItems();
  },
);
</script>
